package com.credit.mola.app.ui.credit.page

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.credit.mola.app.R
import com.credit.mola.app.adapter.AmountAdapter
import com.credit.mola.app.adapter.CreditRepayLableAdapter
import com.credit.mola.app.databinding.PageRepayBinding
import com.credit.mola.app.pro.ProFragment
import com.credit.mola.app.utils.BarUtils
import com.credit.mola.app.utils.DensityUtils
import com.credit.mola.app.utils.config.Configs
import com.credit.mola.app.utils.dialog.NoticeDialog
import com.credit.mola.app.utils.event.EventType
import com.credit.mola.app.utils.event.track.TrackEventManager
import com.credit.mola.app.utils.helper.CustomConfigHelper
import com.credit.mola.app.utils.http.AppUrls
import com.credit.mola.app.utils.http.AppUrls.addCommonParams
import com.credit.mola.app.utils.http.IHttpCallback
import com.credit.mola.app.utils.rv.LinearDecoration
import com.credit.mola.lib_baseadapter.SikadwaOnItemChildClickListener
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject
import java.math.BigDecimal

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/5/22 17:44
 * @Annotation：待还款
 */
class RepayPage: ProFragment() {
    private var _binding: PageRepayBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    private var mAmountAdapter: AmountAdapter? = null
    //还款明细
    private var mLableAdapter: CreditRepayLableAdapter? = null
    //是否展开
    private var isOpen = true

    //公告信息
    private var noticeDialog: NoticeDialog? = null

    override fun getRootView(inflater: LayoutInflater): View {
        _binding = PageRepayBinding.inflate(inflater)
        return binding.root
    }

    override fun initView() {
        _binding?.parentLayout?.setPadding(0, BarUtils.getStatusBarHeight(),0,0)
        initRefreshView()
        initRvAmount()
        initRvRepayListView()
        showOpenOrCloseView()
    }

    override fun initListener() {
        _binding?.imgUser?.setOnClickListener {
            showPersonalDialog("CreditRepayment Page")
            addEvent(EventType.CLICK.CLICK_USER,"CreditRepayment Page")
        }
        _binding?.imgKefu?.setOnClickListener {
            showKefuDialog("CreditRepayment Page")
            addEvent(EventType.CLICK.CLICK_CUSTOMER,"CreditRepayment Page")
        }
        //展开、收起
        _binding?.ivLable?.setOnClickListener {
            isOpen = !isOpen
            showOpenOrCloseView()
        }
        //还款
        _binding?.btnRepayment?.setOnClickListener {
            TrackEventManager.trackEventNow(EventType.CLICK.CLICK_CREDIT_REPAYMENT,"")
            showLoading()
            onPayAction()
        }
    }

    override fun initData() {
        showLoading()
        loadCreditRepayInfoAction()
        addEvent(EventType.PAGE.PAGE_CREDIT_REPAYMENT_START,"")
    }

    fun refreshAction(){
        loadCreditRepayInfoAction()
    }

    /* 初始化刷新 */
    private fun initRefreshView() {
        //禁止加载
        _binding?.refreshLayout?.setEnableLoadMore(false)
        _binding?.refreshLayout?.setEnableAutoLoadMore(false)
        _binding?.refreshLayout?.setOnRefreshListener {
            //发送刷新流程通知
            EventBus.getDefault().post(Configs.Event.PROCESS_REFRESH)
        }
        _binding?.refreshLayout?.setOnLoadMoreListener {
            _binding?.refreshLayout?.finishLoadMore()
        }
    }

    private fun initRvAmount(){
        _binding?.rvAmount?.setHasFixedSize(true)
        _binding?.rvAmount?.isNestedScrollingEnabled = false
        _binding?.rvAmount?.isFocusableInTouchMode = false //不需要焦点
        val decoration = DensityUtils.dp2px(14f)
        _binding?.rvAmount?.addItemDecoration(LinearDecoration(0, decoration, 0, 0))
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.HORIZONTAL
        _binding?.rvAmount?.layoutManager = layoutManager
        mAmountAdapter = AmountAdapter(_binding?.rvAmount)
        mAmountAdapter?.setOnItemChildClickListener { parent, childView, position ->
            val item = this.mAmountAdapter?.getItem(position)
        }
        _binding?.rvAmount?.adapter = mAmountAdapter
    }

    /**
     * 初始化列表
     */
    private fun initRvRepayListView() {
        _binding?.rvRepayInfo?.setHasFixedSize(true)
        _binding?.rvRepayInfo?.isNestedScrollingEnabled = false
        _binding?.rvRepayInfo?.isFocusableInTouchMode = false //不需要焦点
        _binding?.rvRepayInfo?.layoutManager = LinearLayoutManager(context)
//        val topDecoration = DensityUtils.dp2px(8f)
//        _binding?.rvRepayInfo?.addItemDecoration(LinearDecoration(0,0,topDecoration,topDecoration))
        mLableAdapter = CreditRepayLableAdapter(_binding?.rvRepayInfo)
        _binding?.rvRepayInfo?.adapter = mLableAdapter
        _binding?.rvRepayInfo?.itemAnimator = DefaultItemAnimator()
        mLableAdapter?.setOnItemChildClickListener(SikadwaOnItemChildClickListener { _, childView, position ->
        })
    }

    /**
     * 收起
     */
    private fun showOpenOrCloseView(){
        if (isOpen){//展开
            _binding?.rvRepayInfo?.visibility = View.VISIBLE
            _binding?.ivLable?.setImageResource(R.mipmap.img_credit_repay_up_icon)
            addEvent(EventType.CLICK.CLICK_CREDIT_REPAYMENT_INFO_OPEN,"")
        } else {
            _binding?.rvRepayInfo?.visibility = View.GONE
            _binding?.ivLable?.setImageResource(R.mipmap.img_credit_repay_down_icon)
            addEvent(EventType.CLICK.CLICK_CREDIT_REPAYMENT_INFO_CLOSE,"")
        }
    }

    /**
     * 设置还款信息
     */
    @SuppressLint("SetTextI18n")
    fun setRepaymentInfo(data: JSONObject) {
        val amountList = arrayListOf<String>()
        val amountString = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()
        for (i in amountString.indices){
            amountList.add(amountString[i].toString())
        }
        mAmountAdapter?.data = amountList

        _binding?.textRepayAmount?.text = data.optString("repayAmount") + " " + data.optString("currency")
        _binding?.textRepayDate?.text = data.optString("repayDate")
        _binding?.textTotal?.text = data.optString("repayAmount")
        _binding?.textUnit?.text = data.optString("currency")

        val jsArray = data.optJSONArray("detailItemList")
        val dataList = arrayListOf<JSONObject>()
        if (jsArray != null) {
            for (i in 0..<jsArray.length()){
                dataList.add(jsArray.optJSONObject(i))
            }
        }
        mLableAdapter?.data = dataList

        //待还款显示公告信息
        showNoticeDialog()
    }

    /**
     * 待还款 根据配置显示公告Dialog
     */
    private fun showNoticeDialog(){
        if (!CustomConfigHelper.isCmShowNotice()){
            return
        }

        val noticeInfo = CustomConfigHelper.getCmNoticeInfo() ?: return
        val showNum = noticeInfo.optInt("num",1)
        val num = Configs.getSPInt(Configs.SPKEY.CREDIT_MOLA_NOTICE_SHOW_NUM)
        //本地记录的显示公告次数 >= 配置次数
        if (num >= showNum){
            return
        }
        noticeDialog?.let {
            if (it.isShowing){
                return
            }
        }

        Configs.saveSPInt(Configs.SPKEY.CREDIT_MOLA_NOTICE_SHOW_NUM,num+1)
        noticeDialog = NoticeDialog(requireContext(),"Repay Page",object : NoticeDialog.IDialogCallback{
            override fun onClick(view: View?) {
            }
        })
        noticeDialog?.let { dialog ->
            dialog.show()
            dialog.setNoticeTitle(noticeInfo.optString("noticeTitle"))
            dialog.setNoticeMsg(noticeInfo.optString("noticeText"))
        }
    }

    /**
     * 跳转支付H5
     */
    private fun enterPayLink(payUrl: String){
        val uri = Uri.parse(payUrl)
        val intent = Intent(Intent.ACTION_VIEW, uri)
        startActivity(intent)
    }

    /**
     * 获取还款信息
     */
    private fun loadCreditRepayInfoAction(){
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.CREDIT_REPAYMENT_INFO)
            put("oldFlag","YES")
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                obj?.let {
                    setRepaymentInfo(it)
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                _binding?.refreshLayout?.finishRefresh()
            }
        })
    }

    /**
     * 还款
     */
    private fun onPayAction(){
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.CREDIT_REPAYMENT_URL)
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                obj?.let {
                    var repayUrl = it.optString("repayUrl","")
                    if (repayUrl.isEmpty()){
                        repayUrl = it.optString("url")
                    }
                    enterPayLink(repayUrl)
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        //退出待还款页面立即上报所有埋点
        TrackEventManager.trackEventNow(EventType.PAGE.PAGE_CREDIT_REPAYMENT_END,"")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}